<script lang="ts" setup name="UserPage">
import type { User, UserQuery } from '@/types/user'
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
// const userQuery = ref<UserQuery>() ===> 相当于 ===> const userQuery = ref<UserQuery>()
// const userQuery = ref<UserQuery>(null)
const userQuery = ref<UserQuery>({
  page: 1,
  pageSize: 2,
  nickname: ''
})

const list = ref<User[]>([])
const total = ref(0)

const getUserListData = async () => {
  const res = await getUserList(userQuery.value)
  list.value = res.data.data.items
  total.value = res.data.data.total
}

getUserListData()

// 每页多少条改变了
const handleSizeChange = (pageSize: number) => {
  userQuery.value.pageSize = pageSize
  getUserListData()
}

// 当前页发生了改变
const handleCurrentChange = (page: number) => {
  userQuery.value.page = page
  getUserListData()
}

// 新增 & 修改 & 删除相关
const mode = ref('add')
const dialogVisible = ref(false)
const user = ref({
  adminid: '',
  adminname: '',
  nickname: '',
  status: 1 // 1 打开 0 关闭
})

const rules = reactive<FormRules>({
  adminname: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }]
})

const formRef = ref<FormInstance>()
// 提交
const onSubmit = () => {
  formRef.value.validate(async valid => {
    // 如果为假，则直接return
    if (!valid) return

    try {
      if (mode.value === 'edit') {
        await updateUser(user.value)
      } else {
        delete user.value.adminid
        await addUser(user.value)
      }

      // 关闭Dialog
      dialogVisible.value = false

      // 提示成功
      ElMessage.success(mode.value === 'edit' ? '修改成功~' : '新增成功~')

      // 重新获取数据
      if (mode.value === 'add') {
        userQuery.value.page = 1
      }
      getUserListData()
    } catch (error) {}
  })
}

// 修改
const edit = (row: User) => {
  // 这种赋值是浅拷贝
  // user.value = row
  // 这种赋值是深拷贝
  mode.value = 'edit'
  user.value = { ...row }
  // 相当于下面这么写
  // user.value.adminname = row.adminname
  // user.value.nickname = row.nickname
  // user.value.status = row.status
  // ...

  dialogVisible.value = true
}

watch(dialogVisible, value => {
  if (!value) {
    // 要设置成关闭的时候
    // 把模式设置为add
    mode.value = 'add'
    // 关闭的时候，清空内容
    user.value = { status: 1 } as User
    // user.value.adminid = ''
    // user.value.status = 1

    // 把表单内容和校验重置
    formRef.value.resetFields()
  }
})

// 删除
const del = async (adminid: string) => {
  try {
    await ElMessageBox.confirm('确定删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 发请求
    await deleteUser(adminid)

    // 提示
    ElMessage.success('删除成功~')

    // 从第一页从新加载
    userQuery.value.page = 1
    getUserListData()
  } catch (error) {
    console.log(error)
  }
}
</script>

<template>
  <el-card>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索表单 -->
    <el-form :inline="true" size="large" :model="userQuery" style="margin-top: 20px">
      <el-form-item label="昵称">
        <el-input v-model="userQuery.nickname" placeholder="请输入昵称进行搜索" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserListData">搜索</el-button>
        <el-button type="success" @click="dialogVisible = true">+新增用户</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 10px">
    <el-table :data="list">
      <el-table-column label="用户名" prop="adminname" />
      <el-table-column label="用户昵称" prop="nickname" />
      <el-table-column label="用户头像">
        <!-- scope是固定写法，它是一个对象，里面有个属性叫做 row，代表这一行数据 -->
        <!-- 作用域插槽，才能获取值 -->
        <template #default="scope">
          <img style="width: 50px; height: 50px" :src="scope.row.avatar" alt="" />
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-switch
            disabled
            :model-value="row.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="edit(row)">修改</el-button>
          <el-button type="danger" @click="del(row.adminid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="userQuery.page"
      v-model:page-size="userQuery.pageSize"
      :page-sizes="[1, 2, 10]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog v-model="dialogVisible" :title="mode === 'edit' ? '修改用户' : '新增用户'" width="50%">
    <el-form size="large" :model="user" :rules="rules" label-width="180px" ref="formRef">
      <el-form-item label="用户名" prop="adminname">
        <el-input placholder="请输入用户名" :disabled="mode === 'edit'" v-model="user.adminname" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input placholder="请输入用户昵称" v-model="user.nickname" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="user.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
